package	model.code;

import editor.PwnIDE;
import model.Project;
import model.code.line.LineList;
import model.code.line.MultiLineList;
import model.code.line.NameLine;
import model.symbol.Scope;
import model.symbol.Symbol;

import java.io.File;
import java.util.ArrayList;
import java.util.TreeMap;

public class Directory implements Symbol {
	private final	long				id;
	private	NameLine					name;
	private	MultiLineList				description;

	private Directory					parent;
	private Project						project;

	private	TreeMap<String,Document>	documents;
	private	TreeMap<String,CodeFile>	codeFiles;
	private	TreeMap<String,Directory>	directories;

	private	boolean						isExpanded;

	public Directory(String name, String description, Directory parent, Project project) {
		id = Scope.getUniqueID();
		this.name = new NameLine(name.toCharArray(),this);
		this.description = new MultiLineList(null,CodeFileChunk.LOCATION_NOWHERE);
		this.description.replaceAll(description);
		this.parent = parent;
		this.project = project;
		documents = new TreeMap<String,Document>();
		codeFiles = new TreeMap<String,CodeFile>();
		directories = new TreeMap<String,Directory>();
		isExpanded = true;
	}

	public NameLine getName() {
		return name;
	}
	public LineList getDescription() {
		return description;
	}
	public String toString() {
		return name.toString();
	}
	public TreeMap<String, Directory> getDirectories() {
		return directories;
	}

	public TreeMap<String, Document> getDocuments() {
		return documents;
	}

	public TreeMap<String, CodeFile> getCodeFiles() {
		return codeFiles;
	}

	public Directory getParent() {
		return parent;
	}

	public void add(Directory directory) {
		directories.put(directory.getName().toString(),directory);
	}
	public void add(Document document) {
		documents.put(document.getName().toString(),document);
	}
	public void add(CodeFile codeFile) {
		codeFiles.put(codeFile.getName().toString(),codeFile);
		codeFile.setDirectory(this);
	}

	public String getPath() {
		if (parent==null) {
			if (project!=null) {
				if (project.getPath()!=null) {
					// NOTE: The name is not included when the parent is null because this is the root directory of the project.
					return project.getPath()+File.separator;
				}
				return "";
			}
			// NOTE: Directories with no project are assumed to be relative to the PwnIDE directory.
			return PwnIDE.PWNIDE_DIR+name+File.separator;
		}
		return parent.getPath()+name+File.separator;
	}

	public ArrayList<CodeFile> getAllFiles() {
		ArrayList<CodeFile> list = new ArrayList<CodeFile>();
		list.addAll(codeFiles.values());
		for (Directory dir : directories.values()) {
			list.addAll(dir.getAllFiles());
		}
		return list;
	}

	public long getID() {
		return id;
	}

	public boolean isExpanded() {
		return isExpanded;
	}

	public void setExpanded(boolean expanded) {
		isExpanded = expanded;
	}
}
